<template>
  <div class="app-container">
    <pro-table
      ref="tableRef"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :total="total"
      :show-selection="false"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @query="handleQuery"
      @add="handleAdd"
      @refresh="getList"
    >
      <template #action="{ row }">
        <el-button type="primary" link @click="handleAdd(row)">新增</el-button>
        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
        <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
      </template>
    </pro-table>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增菜单' : '编辑菜单'"
      width="700px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <el-tree-select
                v-model="form.parentId"
                :data="menuTree"
                placeholder="请选择上级菜单"
                check-strictly
                :render-after-expand="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="0">目录</el-radio>
                <el-radio :label="1">菜单</el-radio>
                <el-radio :label="2">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="999" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 2">
            <el-form-item label="路由路径" prop="path">
              <el-input v-model="form.path" placeholder="请输入路由路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === 1">
            <el-form-item label="组件路径" prop="component">
              <el-input v-model="form.component" placeholder="请输入组件路径">
                <template #prepend>@/views/</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 0">
            <el-form-item label="权限标识" prop="permission">
              <el-input v-model="form.permission" placeholder="请输入权限标识" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 2">
            <el-form-item label="菜单图标" prop="icon">
              <el-input v-model="form.icon" placeholder="请选择图标" readonly>
                <template #prepend>
                  <el-icon v-if="form.icon">
                    <component :is="form.icon" />
                  </el-icon>
                </template>
                <template #append>
                  <el-button @click="showIconSelect = true">
                    选择图标
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 2">
            <el-form-item label="路由名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入路由名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 2">
            <el-form-item label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio :label="true">显示</el-radio>
                <el-radio :label="false">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type !== 2">
            <el-form-item label="菜单状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === 1">
            <el-form-item label="是否外链">
              <el-radio-group v-model="form.isFrame">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.type === 1">
            <el-form-item label="是否缓存">
              <el-radio-group v-model="form.isCache">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图标选择器 -->
    <el-dialog
      v-model="showIconSelect"
      title="选择图标"
      width="800px"
    >
      <icon-select v-model="form.icon" @select="handleIconSelect" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Select } from '@element-plus/icons-vue'
import ProTable from '@/components/ProTable';
import IconSelect from '@/components/IconSelect'
import {
  getMenuList,
  getMenuTree,
  addMenu,
  updateMenu,
  deleteMenu,
  updateMenuStatus
} from '@/api'

// 列配置
const columns = [
  {
    prop: 'title',
    label: '菜单名称',
    width: '180',
    align: 'left',
    search: true
  },
  {
    prop: 'icon',
    label: '图标',
    width: '60',
    align: 'center',
    render: 'MenuIcon'
  },
  {
    prop: 'sort',
    label: '排序',
    width: '60',
    align: 'center'
  },
  {
    prop: 'permission',
    label: '权限标识',
    width: '180'
  },
  {
    prop: 'component',
    label: '组件路径',
    width: '180'
  },
  {
    prop: 'path',
    label: '路由地址',
    width: '180'
  },
  {
    prop: 'visible',
    label: '显示状态',
    width: '80',
    align: 'center',
    render: 'VisibleTag'
  },
  {
    prop: 'status',
    label: '状态',
    width: '80',
    align: 'center',
    search: true,
    searchType: 'select',
    options: [
      { label: '正常', value: 1 },
      { label: '停用', value: 0 }
    ],
    render: 'StatusSwitch'
  }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const menuTree = ref([])
const showIconSelect = ref(false)

const form = ref({
  parentId: 0,
  title: '',
  name: '',
  path: '',
  component: '',
  permission: '',
  icon: '',
  type: 1,
  sort: 0,
  status: 1,
  visible: true,
  isFrame: false,
  isCache: false
})

const rules = {
  title: [
    { required: true, message: '菜单名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '路由路径不能为空', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '路由名称不能为空', trigger: 'blur' },
    { pattern: /^[A-Z][a-zA-Z0-9]+$/, message: '路由名称必须以大写字母开头', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '组件路径不能为空', trigger: 'blur' }
  ],
  permission: [
    { pattern: /^[a-z][a-z:]+[a-z]$/, message: '权限标识只能包含小写字母和冒号', trigger: 'blur' }
  ]
}

// 获取列表数据
const getList = async (params) => {
  loading.value = true
  try {
    const [menuData, treeData] = await Promise.all([
      getMenuList(params),
      getMenuTree()
    ])
    tableData.value = menuData.data
    menuTree.value = [{
      id: 0,
      title: '顶级菜单',
      children: treeData.data
    }]
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = (params) => {
  getList(params)
}

// 新增菜单
const handleAdd = (row = null) => {
  dialogType.value = 'add'
  form.value = {
    parentId: row ? row.id : 0,
    title: '',
    path: '',
    component: '',
    permission: '',
    icon: '',
    type: 1,
    sort: 0,
    status: 1,
    isFrame: false,
    isCache: false,
    visible: true
  }
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除菜单
const handleDelete = (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('请先删除子菜单')
    return
  }

  ElMessageBox.confirm(
    '确认删除该菜单吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteMenu(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addMenu(form.value)
          ElMessage.success('添加成功')
        } else {
          await updateMenu(form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 图标选择
const handleIconSelect = (icon) => {
  form.value.icon = icon
  showIconSelect.value = false
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

:deep(.el-tree-select) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-tree) {
  margin: 10px 0;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}
</style> 